from django.shortcuts import render, HttpResponse, redirect  # django的渲染，响应，重定向引入模块
from online import models # 引入本app的models模块
import requests   # 引入爬虫模块
from bs4 import BeautifulSoup # 处理下载html文档模块的引用
from lxml import etree   #xpath模块的引用
from matplotlib.figure import Figure # 绘图模块
from matplotlib.backends.backend_agg import FigureCanvasAgg 
from matplotlib.dates import DateFormatter # 数据处理模块
import random # 随机变量模块
import datetime # 时间模块引用
import matplotlib.pyplot as plt
def content(request):
    """
    :param request:
    :return:页面
    云阅读
    """
    current_user = request.session.get('username')

    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
         'Connection': 'close',
    }
    url = "http://tech.163.com/it/"
    # url = "http://www.baidu.com"
    response = requests.get(url, headers=headers)
    html = response.text
    selector = etree.HTML(html)
    title_name_lists = selector.xpath("//div[@class='titleBar clearfix']//h3//a//text()")
    url_lists = selector.xpath("//div[@class='titleBar clearfix']//h3//a//@href")
    list_content = []
    for each in range(len(title_name_lists)):
        title = title_name_lists[each]
        url = url_lists[each]
        dic = {'title': title, 'url': url}
        list_content.append(dic)
    return render(
        request,
        'content.html',
        {'username': current_user, 'list_content': list_content, 'obj': models.Info.objects.filter(userNo=current_user)[0]}
    )

def layout(request):
    return render(request, 'layout.html')

def exam(request):
    """
    :param request:
    :return:
    测试
    """
    #正确答案
    global correct
    #考试题目列表
    global exam_list
    global subject_id
    global test_name
    global clz_id
    current_user = request.session.get('username')

    if request.method == 'GET':
        # 获取考试名称
        test_name = request.GET.get('testName')
        # 获取班级id
        clz_id = request.GET.get('clzId')
        # 获取考试Id
        subject_id = request.GET.get('subjectId')
        # exam_temp 判断该同学是否完成测试
        exam_temp = models.Test.objects.filter(stuId=current_user, subId=subject_id).order_by('index')
        if exam_temp:
            return render(request, 'exam_result.html',
                          {'exam_result': exam_temp, 'username': current_user, 'obj': models.Info.objects.filter(userNo=current_user)[0]}
                          )
        else:
            import random
            num = random.randint(0, 4)
            from utils import randombank
            exam_list = randombank.randomQuestion(num, subject_id)
            right_list = exam_list.values('right')
            temp = []
            for value in right_list:
                temp.append(value['right'])
            correct = temp
            return render(request, 'exam.html',
                          {'examList': exam_list, 'username': current_user, 'obj': models.Info.objects.filter(userNo=current_user)[0]}
                          )

    elif request.method == 'POST':
        # 获取该同学提交测试选择
        sels = request.POST
        stu_submit_sel = []
        for key, value in sels.items():
            stu_submit_sel.append(value)
        #正确的个数
        correct_num = 0
        for i in range(len(correct)):
            models.Test.objects.create(
                **{
                    'stuId': current_user,
                    'examName': test_name,
                    'subId': subject_id,
                    'stuSelect': stu_submit_sel[i],
                    'correctSelect': correct[i],
                    'index': exam_list[i].id,
                    'title': exam_list[i].title,
                    'A': exam_list[i].A,
                    'B': exam_list[i].B,
                    'C': exam_list[i].C,
                    'D': exam_list[i].D
                }
            )
            if correct[i] == stu_submit_sel[i]:
                correct_num = correct_num + 1
        # 分数
        scnum = 100/len(correct)*correct_num
        i = models.Info.objects.filter(userNo=current_user)[0]
        models.Score.objects.create(
            **{
                'score': scnum,
                'name': test_name,
                'cls': models.Classes.objects.get(clsId=clz_id),
                'stuId': current_user,
                'subject': models.Suject.objects.get(subId=subject_id),
                'xx': 1 if i.gender else 0
            }
        )
        models.ReleaseTest.objects.update()
        exam_result = models.Test.objects.filter(stuId=current_user, subId=subject_id).order_by('index')
        return render(
           request,
          'exam_result.html',
          {'exam_result': exam_result, 'username': current_user, 'obj': models.Info.objects.filter(userNo=current_user)[0]}
                      )
    else:
        return HttpResponse("Ok!")

def login(request):
    v = request.session
    if request.method == 'GET':
        return render(request, 'login.html')
    elif request.method == 'POST':
        username = request.POST.get('username')
        pwd = request.POST.get('pwd')

        is_success = models.Info.objects.filter(userNo=username, pwd=pwd)
        if is_success:
            request.session['is_login'] = True
            request.session['username'] = username
            rep = redirect('/index.html')
            return rep
        else:
            return render(request, 'login.html', {'error': '密码或用户名错误！'})
    else:
        return HttpResponse("Url 不存在")

def index(request):
    current_user = request.session.get('username')
    obj = models.Info.objects.filter(userNo=current_user)[0]
    return render(request, 'index.html', {'username': current_user, 'obj': obj})

def finish_list(request):
    current_user = request.session.get('username') 
    score = models.Score.objects.all().filter(stuId=current_user)
    return render(request, "finish_list.html", {"score": score, 'username': current_user, 'obj': models.Info.objects.filter(userNo=current_user)[0]})

def stage(request):
    current_user = request.session.get('username')
    clsName = models.Info.objects.filter(userNo=current_user).values('clsName')
    for x in clsName:
        clsId = models.Classes.objects.filter(clsName=x['clsName']).values('clsId')
        for y in clsId:
            release = models.ReleaseTest.objects.filter(isTestFinish=0, clz_id=y['clsId'])
            return render(request, "stage.html", {'release': release, 'username': current_user, 'obj': models.Info.objects.filter(userNo=current_user)[0]})

def cnblogs(request):
    current_user = request.session.get('username')
    """
    获取博客园精华的帖子
    :param request:
    :return:
    """
    import random
    rang = random.randint(0, 80)
    url = ("https://www.cnblogs.com/pick/%s/" %(rang))
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
         'Connection': 'close',
    }
    response = requests.get(url, headers=headers)
    html = response.text
    soup = BeautifulSoup(html, "lxml")
    result = soup.select('.titlelnk')
    content = []
    for each in result:
        name = each.text
        urls = each['href']
        dic = {'title': name, 'url': urls}
        content.append(dic)
    return render(request, "cnblogs.html", {'content': content, 'username': current_user, 'obj': models.Info.objects.filter(userNo=current_user)[0]})

def csdn(request):
    current_user = request.session.get('username')
    """
    爬csdn的https://blog.csdn.net/nav/iot今日推荐
    :param request:
    :return:
    """
    url = 'https://blog.csdn.net/nav/iot'
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"
    }
    response = requests.get(url, headers=headers)
    html = response.text
    soup = BeautifulSoup(html, 'lxml')
    csdn_name_lists = soup.select('.company_name')
    content = []
    for each in csdn_name_lists:
        name = each.text
        urls = each.find('a')['href']
        dic = {'title': name, 'url': urls}
        content.append(dic)
    return render(request, 'csdn.html', {'content': content, 'username': current_user, 'obj': models.Info.objects.filter(userNo=current_user)[0]})

def oschina(request):
    """
    获取开源中国
    :param request:
    :return:
    """
    current_user = request.session.get('username')
    url = 'https://www.oschina.net/project/'
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"
    }
    response = requests.get(url, headers=headers)
    html = response.text
    html_text = etree.HTML(html)
    oschina_name_lists = html_text.xpath("//div[@class='panel-wrapper hot-article']//div[@class='panel-list']//a//text()")
    oschina_url_lists = html_text.xpath("//div[@class='panel-wrapper hot-article']//div[@class='panel-list']//a//@href")
    name_lists = []

    for each in range(len(oschina_name_lists)):
        name_lists.append(oschina_name_lists[each].strip())
    temp_lists = []

    for each in range(len(name_lists)):
        if each % 3 == 0:
            temp_lists.append(name_lists[each])

    content = []
    for each in range(len(temp_lists)):
        name = temp_lists[each]
        url = oschina_url_lists[each]
        dic = {'title': name, 'url': url}
        content.append(dic)
    return render(request, 'oschina.html', {'content': content, 'username': current_user, 'obj': models.Info.objects.filter(userNo=current_user)[0]})
def iot(request):
    """
    物联网智库
    :param request:
    :return:
    """
    current_user = request.session.get('username')
    url = 'http://www.iot101.com/'
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"
    }
    response = requests.get(url, headers=headers)
    response.encoding = response.apparent_encoding
    html = response.text
    html_text = etree.HTML(html)
    iot_name = html_text.xpath('//div[@class="newright"]//ul[@class="conlist"]//a//text()')
    iot_list = html_text.xpath('//div[@class="newright"]//ul[@class="conlist"]//@href')
    list_content = []
    for each in range(len(iot_name)):
        title = iot_name[each]
        url = 'http://www.iot101.com'+iot_list[each]
        print(url)
        dic = {'title': title, 'url': url}
        list_content.append(dic)
    return render(request, 'iot.html', {'content': list_content, 'username': current_user, 'obj': models.Info.objects.filter(userNo=current_user)[0]})

def answer(request):
    """

    :param request:
    :return:
    """
    return render(request, "answer.html")

def analyze(request):
    """
    答疑区列表
    :param request:
    :return:
    """
    current_user = request.session.get('username')
    release = models.ReleaseTest.objects.filter(isTestFinish=0)
    return render(request, "analyze.html", {'release': release, "username": current_user, 'obj': models.Info.objects.filter(userNo=current_user)[0]})

def discuss(request):
    """
    答疑详细讨论页
    :param request:
    :return:
    """
    current_user = request.session.get('username')
    subject_id = request.GET.get('subjectId')
    answer_lists = models.Answer.objects.all().filter(subject_id=subject_id).order_by('-time')
    # for each in answer_lists:
    #     print(each.problem)
    #     # each.values('comment__content')
    #     for x in each.comment_set.all():
    #         print(x.info.userName)
    return render(request, "discuss.html",
                  {'answer_lists': answer_lists, 'subject_id': subject_id, "username": current_user, 'obj': models.Info.objects.filter(userNo=current_user)[0]})

def add_discuss(request):
    current_user = request.session.get('username')
    if request.method == "POST":
        import time
        # 获取当前时间
        current_time = time.strftime('%Y-%m-%d', time.localtime(time.time()))
        textarea = request.POST.get('textarea')
        answer_id = request.POST.get('answer_id')
        username = request.POST.get('username')
        info = models.Info.objects.filter(userNo=username)
        for x in info:
            models.Comment.objects.create(**{
                'content': textarea,
                'answer_id': answer_id,
                'info_id': x.pk,
                'time': current_time
            })
        import json
        for x in info:
            info_basic = {'current_time': current_time, 'textarea': textarea, 'username': x.userName, 'obj': models.Info.objects.filter(userNo=current_user)[0]}
            return HttpResponse(json.dumps(info_basic))
def add_answer(request):
    if request.method == "POST":
        import time
        # 获取当前时间
        current_time = time.strftime('%Y-%m-%d', time.localtime(time.time()))
        textarea = request.POST.get('textarea')
        subject_id = request.POST.get('subject_id')
        username = request.POST.get('username')
        info = models.Info.objects.filter(userNo=username)
        for x in info:
            models.Answer.objects.create(**{
                'problem': textarea,
                'subject_id': subject_id,
                'info_id': x.pk,
                'time': current_time
            })
        current_user = request.session.get('username')
        answer_lists = models.Answer.objects.all().filter(subject_id=subject_id).order_by('-time')
        # for each in answer_lists:
        #     print(each.problem)
        #     # each.values('comment__content')
        #     for x in each.comment_set.all():
        #         print(x.info.userName)
        return render(request, "discuss.html",
                      {'answer_lists': answer_lists, 'subject_id': subject_id, "username": current_user, 'obj': models.Info.objects.filter(userNo=current_user)[0]})
def word(request):
    current_user = request.session.get('username')
    return render(
        request,
        "",
        {'obj': models.Info.objects.filter(userNo=current_user)[0]}
    )

def homewordlist(request):
    current_user = request.session.get('username')
    word_list = models.HomeWord.objects.filter(isFinish=False, teacherNo=current_user).values('a', 'start', 'end', 'subject_id').distinct()
    return render(
        request,
        "homeword_llist.html",
        {
            "username": current_user,
            'obj': models.Info.objects.filter(userNo=current_user)[0],
            'word_list': word_list
        }
    )
def detail_home(request):
    current_user = request.session.get('username')
    if request.method == 'POST':
        subjectId = request.POST.get('subjectId')
        homeName = request.POST.get('homeName')
        userNo = request.POST.get('userNo')
        i = models.Info.objects.filter(userNo=current_user)[0]
        c = models.Classes.objects.filter(clsName=i.clsName)[0]
        homeNameList = models.HomeWord.objects.filter(clz_id=c.clsId, a=homeName, subject_id=subjectId)
        return render(
            request,
            "detail_word.html",
            {
                "username": current_user,
                 'obj': models.Info.objects.filter(userNo=current_user)[0],
                'homeNameList': homeNameList
             }
        )
def fix_up(request):
    current_user = request.session.get('username')
    if request.method == "GET":
        cls = models.Suject.objects.all()
        c = models.Classes.objects.all()
        return render(
            request,
            "fix_up.html",
            {
                "username": current_user,
                'obj': models.Info.objects.filter(userNo=current_user)[0],
                'cls': cls,
                'c': c
            }
        )
    elif request.method == "POST":
        import time
        current_time = time.strftime('%Y-%m-%d', time.localtime(time.time()))
        username = request.POST.get('username')
        text = request.POST.getlist('assignment', '')
        time = request.POST.get('time')
        subId = request.POST.get('subjectId')

        proName = request.POST.get('aName')
        clssId = request.POST.get('clsId')
        for x in text:
            models.HomeWord.objects.create(**{
                'start': current_time,
                'end': time,
                'assignment': x,
                'teacherNo': username,
                'isFinish': False,
                'a': proName,
                'b': '0',
                'subject_id': subId.strip(),
                'clz_id': str(clssId.strip())
            })
        return render(
            request,
            "homeword_llist.html",
            {
                "username": current_user,
                'obj': models.Info.objects.filter(userNo=current_user)[0],
                'word_list': models.HomeWord.objects.filter(isFinish=False).values('a', 'start', 'end', 'subject_id').distinct()
            }
        )

def stu_home_list(request):
    current_user = request.session.get('username')
    clsName = models.Info.objects.filter(userNo=current_user).values('clsName')
    for x in clsName:
        clsId = models.Classes.objects.filter(clsName=x['clsName']).values('clsId')
        for y in clsId:
            word_list = models.HomeWord.objects.filter(isFinish=False, clz_id=y['clsId']).values('a', 'start', 'end',
                                                                                                  'subject_id').distinct()
    return render(
        request,
        "stu_home_word.html",
        {
            "username": current_user,
            'obj': models.Info.objects.filter(userNo=current_user)[0],
            'word_list': word_list
          }
        )
def teacher_look_test(request):
    current_user = request.session.get('username')
    clsName = models.Info.objects.filter(userNo=current_user).values('clsName')
    for x in clsName:
        clsId = models.Classes.objects.filter(clsName=x['clsName']).values('clsId')
        for y in clsId:
            release = models.ReleaseTest.objects.filter(isTestFinish=0, clz_id=y['clsId'])
            return render(request, "teacher_stage.html", {'release': release, 'username': current_user, 'obj': models.Info.objects.filter(userNo=current_user)[0]})
def gen_mat(request):
    sub = request.POST.get('sub')
    print(sub, "....//....")
    from pylab import mpl
    mpl.rcParams['font.sans-serif'] = ['SimHei']
    fig = Figure(figsize=(12, 4))

    # ax = fig.add_subplot(1, 2, 1)
    # x = []
    # y = []
    # now = datetime.datetime.now()
    # delta = datetime.timedelta(days=1)
    # for i in range(10):
    #     x.append(now)
    #     now += delta
    #     y.append(random.randint(0, 100))
    # ax.plot_date(x, y, '-')
    # ax.set_title("score")
    # ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
    # fig.autofmt_xdate()
    # 设置散点图
    ax1 = fig.add_subplot(1, 2, 1)
    score = models.Score.objects.filter(xx=0, subject_id=sub)  #女生
    score1 = models.Score.objects.filter(xx=1, subject_id=sub)  #男生
    score_list1 = []
    gender_list1 = []
    score_list2 = []
    gender_list2= []
    cls = score[0].cls.clsName
    for each in score:
        gender_list1.append(int(each.id))
        score_list1.append(each.score)
    for each in score1:
        gender_list2.append(int(each.id))
        score_list2.append(each.score)
    ax1.scatter(score_list1, gender_list1, s=10, color='r', alpha=0.75)
    ax1.scatter(score_list2, gender_list2, s=10, color='b', alpha=0.75)
    ax1.set_title("%s男女成绩分布"%(cls))
    ax1.set_xlabel("score")
    ax1.set_ylabel("id")
    score2 = models.Score.objects.filter(subject_id=sub)
    s = []
    for each in score2:
        s.append(each.score)
    #描绘直方图
    ax2 = fig.add_subplot(1, 2, 2)
    ax2.hist(s, bins=10)
    ax2.grid(True)
    ax2.legend(loc=0)
    ax2.set_ylabel("number")
    ax2.set_xlabel("score")
    ax2.set_title("%s成绩分布"%(cls))

    canvas = FigureCanvasAgg(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    plt.close(fig)
    return response
def add_test(request):
    current_user = request.session.get('username')
    if request.method == "GET":
        cls = models.Suject.objects.all()
        c = models.Classes.objects.all()
        return render(
            request,
            "add_test.html",
            {
                "username": current_user,
                'obj': models.Info.objects.filter(userNo=current_user)[0],
                'cls': cls,
                'c': c
            }
        )
    elif request.method == "POST":
        import time
        current_time = time.strftime('%Y-%m-%d', time.localtime(time.time()))
        username = request.POST.get('username')
        time = request.POST.get('time')
        subId = request.POST.get('subjectId')
        proName = request.POST.get('aName')
        clssId = request.POST.get('clsId')
        models.ReleaseTest.objects.create(**{
                'start': current_time,
                'name': proName,
                'end': time,
                'teacher': username,
                'isTestFinish': False,
                'subject_id': subId.strip(),
                'clz_id': str(clssId.strip())
        })
        return render(
            request,
            "stage_teacher.html",
            {
                "username": current_user,
                'obj': models.Info.objects.filter(userNo=current_user)[0],
                'release': models.ReleaseTest.objects.filter(teacher=current_user)
            }
        )

def add_test_bank(request):
    current_user = request.session.get('username')
    if request.method == "GET":
        cls = models.Suject.objects.all()
        return render(
            request,
            "add_test_bank.html",
            {
                "username": current_user,
                'obj': models.Info.objects.filter(userNo=current_user)[0],
                'cls': cls,
            }
        )
    elif request.method == "POST":
        username = request.POST.get('username')
        text = request.POST.get('assignment', '')
        subId = request.POST.get('subjectId')
        aName = request.POST.get('aName')
        bName = request.POST.get('bName')
        cName = request.POST.get('cName')
        dName = request.POST.get('dName')
        rigth = request.POST.get('rigth')
        print(username, text, subId, aName, bName, cName, dName, rigth)
        models.ExamBank.objects.create(**{
                'title': text,
                'userNo': username,
                'right': rigth,
                'A': aName,
                'B': bName,
                'C': cName,
                'D': dName,
                'subject_id': subId.strip(),
            })
        cls = models.Suject.objects.all()
        return render(
            request,
            "add_test_bank.html",
            {
                "username": current_user,
                'obj': models.Info.objects.filter(userNo=current_user)[0],
                'cls': cls,
            }
        )